#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os
import xml.dom.minidom


def findfiles(path, t):
    '''
    遍历查找目录下的所有jpg文件名
    :param path:
    :param t:
    :return:
    '''
    files = os.listdir(path)
    for f in files:
        npath = path + '/' + f
        if(os.path.isfile(npath)):
            if(os.path.splitext(npath)[1] ==".jpg"):
                t.append(os.path.splitext(f)[0])
    return

def statisticBbox(inputfolder_xml, filename, classes, counterList):
    '''
    对指定目录下的指定名字的xml文件信息进行统计，并保存到指定文本内
    :param inputfolder_xml:
    :param filename:
    :param statisticTxtPath:
    :return:vi
    '''

    #打开标注数据xml文件
    xmlpath = inputfolder_xml + '/' + filename + '.xml'
    DOMTree = xml.dom.minidom.parse(xmlpath)
    collection = DOMTree.documentElement

    skuname = collection.getElementsByTagName("name")
    skudifficult = collection.getElementsByTagName("difficult")
    rectNum = len(skuname)

    for i in range(rectNum):
        name = skuname[i].childNodes[0].data
        difficult = int(skudifficult[i].childNodes[0].data)
        if 1 == difficult:
            continue
        if name not in classes:
            print("sku name not in list: " + name + "int img " + filename)
            classes.append(name)
            counterList.append(1)
        else:
            idx = classes.index(name)
            counterList[idx] = counterList[idx] + 1



if __name__=="__main__":
    '''
    主函数
    输入：jpg图像目录，xml目录
    输出：统计xml数据中出现的sku种类，以及各种类sku的bbox出现次数 
    '''
    print("version:2018.11.14  author: lhf")
    wd = os.getcwd()

    errstatus = 0 #0无错误，-1有错误

    #sku列表
    classes = [
        "130101001",
	"130101002",
	"130101003",
	"130302001",
	"130302002",
	"130302003",
	"130302004",
	"130303001",
	"170102001",
	"180301001",
	"180301002",
	"180301003",
	"190312001",
	"190505005",
	"200101001",
	"200201001"]
    length = len(classes)  # 原计划的sku种类数量
    counterList = []
    for i in range(length):
        counterList.append(0)

    #输入输出路径
    inputfolder_img = "./xmls1"
    inputfolder_xml = "./xmls1"
    statisticTxtPath = "./statistic.txt"

    #检索所有jpg文件名
    jpgfilenamelist = []
    findfiles(inputfolder_img, jpgfilenamelist)
    print("found %d jpg files." % len(jpgfilenamelist))
    print("")

    #统计所有xml文件中的sku数据
    for filename in jpgfilenamelist:
        xmlpath = inputfolder_xml + "/" + filename + ".xml"
        #print("processing " + xmlpath)
        if (False == os.path.exists(xmlpath)):
            print("ERROR! %s's xml file does not exists!" % filename)
            errstatus = -1
            break
        else:
            #print("processing %s ..." % filename)
            statisticBbox(inputfolder_xml, filename, classes, counterList)

    #保存信息至指定txt
    f1 = open(statisticTxtPath, 'w')
    for i in range(len(classes)):
        if i == length:
            f1.write("\n")
            f1.write("=============sku below not in planned list=========================\n")

        f1.write(classes[i] + "\t" + str(counterList[i]))
        if 0 == counterList[i]:
            f1.write("\tnotice!")
        f1.write('\n')
    f1.close()

    #jpgfilenamelist.clear()

